package io.coderyeah.ymcc.service.impl;

import com.alibaba.fastjson2.JSON;
import io.coderyeah.ymcc.dto.GoodsDTO;
import io.coderyeah.ymcc.service.ITrolleyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author lqs
 * @date 2022/11/6 10:14
 */
@Service
@Slf4j
public class TrolleyServiceImpl implements ITrolleyService {
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    public void save(GoodsDTO goodsDTO) {
        // 保存物品到redis 用hash
        redisTemplate.opsForHash().put("cache:goods:" + goodsDTO.getUserId().toString(), goodsDTO.getId().toString(), goodsDTO);
    }

    @Override
    public List<GoodsDTO> queryByUserId(Long userId) {
        // 查询用户的所有商品集合
        List<Object> values = redisTemplate.opsForHash().values("cache:goods:" + userId.toString());
        List<GoodsDTO> goodsDTOS = JSON.parseArray(JSON.toJSONString(values), GoodsDTO.class);
        log.info("values:{}", values);
        log.info("goodsDTOS:{}", goodsDTOS);
        return goodsDTOS;
    }

    @Override
    public void delete(Long userId, Long goodsId) {
        // 根据key和field移除goods
        Long delete = redisTemplate.opsForHash().delete("cache:goods:" + userId.toString(), goodsId.toString());
        log.info("delete:{}", delete);
    }
}
